﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Security;
using Monitor.Models.Json;
using Monitor.Repository.Development;
using Monitor.Repository.UserRepository.LinqModel;
using WebMatrix.WebData;

namespace Monitor.Controllers.ApiControllers.Administrator
{

    public class UserController : MainApiController
    {
        #region инициализация

        protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
        {
            try
            {
                if (!WebSecurity.Initialized)
                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "UserId", "UserName", autoCreateTables: true);
            }
            catch (Exception e)
            {
                ErrorLogger.Error("Инициализация UserController", e);
            }

            base.Initialize(controllerContext);
        }


        #endregion

        #region GetAction

        public IEnumerable<UserRow> Get()
        {
            try
            {
                return UserRepository.Users.Select(user => user.GetUserRow()).ToArray();
            }
            catch (Exception e)
            {
                ErrorLogger.Fatal(this.ControllerContext, e);
            }
            return null;
        }

        public UserModel Get(string login)
        {
            try
            {
                UserModel result = UserRepository.GetUser(login).GetUserModel();
                if (result != null)
                {
                    result.Service.Name = DataRepository.ClassificatorRepository.GetById(result.Service.Id).FullName;
                    foreach (ClassifElement car in result.CarList)
                    {
                        Car carInUser = CurrentUser.Cars.FirstOrDefault(n => n.Fk_CarId == car.HidenId);
                        if (carInUser != null)
                        {
                            car.Id = carInUser.CarId;
                            car.Comment = carInUser.IconClass;
                        }
                        car.Name = DataRepository.CarRepository.GetCarById(car.HidenId).CarName();
                    }
                }
                return result;
            }
            catch (Exception e)
            {
                ErrorLogger.Error(this.ControllerContext, e);
            }
            return null;
        }

        #endregion

        #region PostAction

        public HttpResponseMessage Post(string login)
        {
            try
            {
                bool freeLogin = UserRepository.FreeLogin(login);
                return Request.CreateResponse(HttpStatusCode.OK,new{Success=true, Result=freeLogin});
            }
            catch (Exception e)
            {
                ErrorLogger.Error(this.ControllerContext, e);
                return Request.CreateResponse(HttpStatusCode.OK, new { Success = false});
            }

        }
        
        #endregion

        #region PutAction

        public HttpResponseMessage Put(UserInputModel model)
        {
            if (model.IsValid)
            {
                try
                {
                    model.ListOfCar =
                               CurrentUser.Cars.Join(model.ListOfCar.Distinct(), n => n.CarId, m => m, (n, m) => n.Fk_CarId).ToArray();

                    if (model.IsNewUser)
                    {
                        if (!UserRepository.AddNewUser(model))
                        {
                            return Request.CreateResponse(HttpStatusCode.OK, "Добавить пользователя не удалось. Возможно, пользователь с данным логином уже зарегистрирован в системе");
                        }
                    }
                    else
                    {
                        if (!UserRepository.UpdateUser(model))
                        {
                            return Request.CreateResponse(HttpStatusCode.OK,
                                                          "Обновить пользователя не удалось. Возможно, пользователь с данным логином не зарегистрирован в системе");
                        }
                    }
                    
                }
                catch (Exception e)
                {
                    ErrorLogger.Fatal(this.ControllerContext, e);
                    return Request.CreateResponse(HttpStatusCode.OK, "Извините, пожалуйста, но произошла ошибка при на сервере. Администратор уже оповещен.");
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, "Ошибка в данных");
            }
        }

        #endregion

        #region Delete

        public HttpResponseMessage Delete(string login)
        {
            if(login.ToLower()!="belaz")
            {
                try
                {
                    UserRepository.DeleteUser(login);
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
                catch (Exception e)
                {
                    ErrorLogger.Error(this.ControllerContext,e);
                    return Request.CreateResponse(HttpStatusCode.OK,"Произошла ошибка. Администратор уже оповещен.");
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, "Такой учетной записи не найдено");
            }
        }

        #endregion

    }

    #region вспомогательный метод

    static class UserControllerHelper
    {
        static Dictionary<string, string> rolesToString = new Dictionary<string, string>()
                                                                     {
                                                                         {"worker", "Наладчик"},
                                                                         {"service", "Сервисный центр"},
                                                                         {"admin", "Администратор"}
                                                                     }; 
        private static string RolesToString(string role)
        {
            if (string.IsNullOrEmpty(role))
                return "Неуказана";
            else
            {
                return (rolesToString.ContainsKey(role)) ? rolesToString[role] : "Неизвестная";
            }
        }
        public static UserRow GetUserRow(this User obj)
        {
            if(obj!=null)
            {
                return new UserRow
                           {
                               Login = obj.UserName,
                               Name = obj.Name,
                               Family = obj.Family,
                               Role = RolesToString(Roles.GetRolesForUser(obj.UserName).FirstOrDefault()),
                               CountOfCar = obj.Cars.Count()
                           };
            }else
            {
                return null;
            }
           
        }
        public static UserModel GetUserModel(this User obj)
        {
            if (obj != null)
            {
                return new UserModel
                           {
                               Login = obj.UserName,
                               Name = obj.Name,
                               Family = obj.Family,
                               Role = Roles.GetRolesForUser(obj.UserName).FirstOrDefault(),
                               Service = new ClassifElement()
                                             {
                                                 Id = 10010000001
                                             },
                               CarList = obj.Cars.Select(n => new ClassifElement()
                                                                  {
                                                                      Id = n.CarId,
                                                                      Comment = n.IconClass,
                                                                      HidenId = n.Fk_CarId
                                                                  }).ToArray()
                           };
            }
            else
            {
                return null;
            }

        }
    }

    #endregion
}
